
package com.pssmobile.genericglossary.visual;

import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.decor.BackgroundFactory;

import com.pssmobile.genericglossary.common.ITermsNavigatorListener;
import com.pssmobile.genericglossary.common.TermsNavigator;
import com.pssmobile.genericglossary.data.DataAdapter;
import com.pssmobile.genericglossary.data.Term;

/**
 * 
 */
public class TermsListField extends ListField implements ListFieldCallback, ITermsNavigatorListener {
    
    public TermsListField() {
        super(0, USE_ALL_HEIGHT | USE_ALL_WIDTH);
        setCallback( this );
        setBackground(BackgroundFactory.createSolidTransparentBackground( Color.WHITE, 0 ));
        setEmptyString("<< No terms found >>", 0);
    }
    
    public void drawListRow( ListField list, Graphics g, int index, int y, int w ) {
        
        Term term = null;
        DataAdapter db = DataAdapter.getInstance();
        int id = TermsNavigator.getInstance().getTermIDByIndex(index);
        try {
            term = db.getTermById( id );
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }        
        
        int x_pos = 0;
        int y_pos = y;
        
        // 2. Clear item background
        g.setGlobalAlpha(0);
        g.setBackgroundColor(Color.WHITE);
        g.clear();
        g.setGlobalAlpha(255);
        
        // Name
        String text = term.name;
        g.drawText(text, x_pos, y_pos);
    }
    
    public Object get(ListField list, int index) {
        return new Integer(TermsNavigator.getInstance().getTermIDByIndex(index));
    }
    
    public int indexOfList(ListField list, String p, int s) {
        return 0;
    }
    
    public int getPreferredWidth(ListField list) {
        return Display.getWidth();
    }

    public void currentTermChanged(int termID) {
        setSelectedIndex(TermsNavigator.getInstance().getTermIndexByID( termID ));
    }
}
